Skip to main content

Sudoku Solver

Question

Given a 9x9 grid containing numbers from 1 to 9, write an algorithm to fill in the missing numbers in the grid such that each row, column, and 3x3 subgrid contains all of the digits from 1 to 9.

Example 1
None

Solution

all//Sudoku Solver.py


def SudokuSolver(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find

for i in range(1,10):
if valid(board, i, (row, col)):
board[row][col] = i

if SudokuSolver(board):
return True

board[row][col] = 0

return False

def valid(board, num, pos):
# Check row
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False

# Check column
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False

# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3

for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if board[i][j] == num and (i,j) != pos:
return False

return True

def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j) # row, col

return None